package com.boxuegu.concurrent.stop;

/**
 * 中断处于阻塞中的线程
 */
public class InterruptBlockedThread {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnableThreadImp = () -> {
            Thread currentThread = Thread.currentThread();
            while(!currentThread.isInterrupted()) {
                System.out.println("Runnable-Thread");
                try {
                    Thread.sleep(200); // 让子线程休眠200ms
                } catch (InterruptedException e) { // 同时，中断状态设置为false
//                    e.printStackTrace();
                    currentThread.interrupt();
                }
            }
        };
        Thread runnable = new Thread(runnableThreadImp);
        runnable.start();
        try {
            Thread.sleep(20); // 让主线程休眠20ms
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 请求中断线程，即设置当前线程的的中断状态为true
        // 当此方法尝试中断一个处于阻塞状态的线程时，该线程会抛出一个InterruptedException
        // 并将此线程的中断状态，清除为false
        runnable.interrupt();
    }
}
